package controllers

import (
	"encoding/json"

	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
)

type BrandController struct {
	BaseController
}

func (c *BrandController) Prepare() {
	c.BaseController.Prepare()

	c.Data["activeSidebarUrl"] = "/brand/index"
}

func (c *BrandController) Index() {
	c.checkAuthor("brand/index")

	c.display("", "brand/index_footerjs.html")

}

func (c *BrandController) DataGrid() {

	c.checkAuthor("brand/index")

	var qs models.ErpBrandQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
	qs.DepartmentId = c.curUser.DepartmentId
	data, count := models.ErpBrandPageList(&qs)

	c.jsonDataTable(count, data)
}

func (c *BrandController) Delete() {
	c.checkAuthor("brand/delete")

	id, _ := c.GetInt64("id")

	if err := models.ErpBrandDel(id, c.curUser.DepartmentId); err != nil {
		c.jsonResult(enums.JRCodeFailed, "删除失败:"+err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "删除成功", "")
	}
}

func (c *BrandController) Edit() {
	c.checkAuthor("brand/edit")

	if c.Ctx.Input.IsPost() {
		c.Save()
	}

	id, _ := c.GetInt64(":id")

	var err error

	m := new(models.ErpBrand)
	m.Id = id

	if id > 0 {
		m, err = models.GetErpBrandById(id)
		if err != nil {
			c.pageError("找不到指定数据")
		}
		if m.DepartmentId != c.curUser.DepartmentId {
			c.pageError("找不到指定数据")
		}
	}

	c.Data["m"] = m

	c.display("", "brand/edit_footerjs.html", "shared/layout_dialog.html")

}

func (c *BrandController) Save() {

	m := models.ErpBrand{}

	if err := c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "提交参数错误", "")
	}
	m.DepartmentId = c.curUser.DepartmentId
	if m.Id == 0 { //新增
		if _, err := models.ErpBrandAdd(&m); err != nil {
			c.jsonResult(enums.JRCodeFailed, "新增失败:"+err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "新增成功", "")
		}
	} else { //修改
		if mr, err := models.GetErpBrandById(m.Id); err != nil {
			c.jsonResult(enums.JRCodeFailed, "获取失败:"+err.Error(), "")
		} else {
			m.Status = mr.Status
		}

		if err := m.ErpBrandEdit(); err != nil {
			c.jsonResult(enums.JRCodeFailed, "修改失败:"+err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "修改成功", "")
		}
	}

}
